package johnkkk.com.test;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLES32;
import android.opengl.Matrix;
import android.os.Build;

import com.code.AbsGLRender;
import com.system.Camera;

import java.util.ArrayList;
import java.util.List;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import johnkkk.com.gl3x.R;
import johnkkk.com.obj.SkyCube;
import johnkkk.com.system_k.Terrain;

/**
 * @Author: clm
 * @Date: 2018-10-27
 */

public class CameraGLRender extends AbsGLRender {
    private Camera mCamera;
    private Terrain mTerrain;
    public CameraGLRender(Context context) {
        super(context);
    }

    @Override
    protected Camera getCamera() {
        mCamera = new Camera();
        return mCamera;
    }

    @Override
    protected void onCreate(GL10 gl10, EGLConfig eglConfig) {
        GLES32.glEnable(GLES32.GL_DEPTH_TEST);
        //GLES32.glEnable(GLES32.GL_CULL_FACE);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreateRootNode() {
        //创建根节点时
        //添加摄像机
        mRootNode.addChild(mCamera);
        //添加测试物体
//        BulletBox box = new BulletBox("box");
//        mRootNode.addChild(box);
        //添加terrain
        mTerrain = new Terrain("terrain");
        mRootNode.addChild(mTerrain);
        //添加天空盒
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;//Opengl需要非压缩形式的原始数据
        List<Bitmap> bitmaps = new ArrayList<>();
        bitmaps.add(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.right, options));
        bitmaps.add(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.left, options));
        bitmaps.add(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.top, options));
        bitmaps.add(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.bottom, options));
        bitmaps.add(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.front, options));
        bitmaps.add(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.back, options));
        mRootNode.addChild(new SkyCube("sky", mCamera, bitmaps));
    }

    @Override
    public void onDrawFrame(GL10 gl10) {
        super.onDrawFrame(gl10);
        //更新摄像机
        float x = mCamera.eye.vec[0];
        float z = mCamera.eye.vec[2];
        if(x > 0 && z > 0 && x < mTerrain.getWidth() && z < mTerrain.getHeight()){
            mCamera.eye.vec[1] = mTerrain.getTerrainHeightFast(x, z) + 5.0f;
        }
    }

    @Override
    protected void onInitChange(GL10 gl10, int w, int h) {
        Matrix.perspectiveM(mP_matrix, 0, mCamera.mViewAngle, w / h, mCamera.mNear, mCamera.mFar);
        GLES20.glViewport(0, 0, w, h);
        mCamera.mP_matrix = mP_matrix;
    }
}
